<template>
  <div class="grid-container">
    <div class="page-bread">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/outstorage_action/adjust' }">在库调整</el-breadcrumb-item>
        <el-breadcrumb-item>在库调整处理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="detail-content">
      <el-tabs activeName="detail">
        <el-tab-pane label="受注出库单" name="detail">
          <el-row>
            <el-col :span="10">
              <div class="detail-item">
                <span>受注编号</span>
                <div>{{ order.AdjustNo }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>出库编号</span>
                <div>{{ order.OutStcNo }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>出库场所编号</span>
                <div>{{ order.PlaceCD }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>出库库位代码</span>
                <div>{{ order.FineFlg }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>商店</span>
                <div>{{ order.customer ? order.customer.ShopSignNM : order.CustomerCd }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>送货地代码</span>
                <div>{{ order.deliver ? order.deliver.DeliverAdd : order.DeliverAddCD }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>受注日期</span>
                <div>{{ order.AdmYMD }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>销售订单类型</span>
                <div>{{ order.AUART }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>备注特殊送货地地址</span>
                <div>{{ order.DeliverAddMemo }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>备注</span>
                <div>{{ order.Memo }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>POS订单号</span>
                <div>{{ order.ApplyNo }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="detail-item">
                <span>创建时间</span>
                <div>{{ order.created_at }}</div>
              </div>
            </el-col>
          </el-row>
          <div class="btn-box">
            <el-button :disabled="buttonDisabled" type="primary" @click="getSheet">拣货单</el-button>
            <el-button :disabled="buttonDisabled" type="primary" @click="getPDF">交货单</el-button>
            <el-button :disabled="buttonDisabled" type="primary" @click="accept">验收单</el-button>
            <el-button :disabled="buttonDisabled" type="primary" @click="binning">装箱汇总单</el-button>
            <el-button :disabled="buttonDisabled" type="primary" @click="pinxiangList">拼箱清单</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="detail-content">
      <div class="btn-box">
        <el-button
          :disabled="buttonDisabled"
          type="primary"
          v-if="order.tag && order.tag.status === '复核中' || order.tag && order.tag.status === '拣货中'"
          @click="rollback"
        >回退</el-button>
        <el-button
              :disabled="buttonDisabled"
              type="primary"
              v-if="order.tag && order.tag.status === '待发运' && is_need_code === '是'"
              @click="showCodeDialog"
      >防串货</el-button>
        <el-button
          :disabled="buttonDisabled"
          type="primary"
          v-if="!order.tag || order.tag.status !== '发货完成'"
          @click="doChange"
        >{{ buttonName }}</el-button>
      </div>
      <el-tabs activeName="table">
        <el-tab-pane label="商品明细" name="table">
          <div class="statistic-content">
            <p>
              统计：
              <span>产品种类：{{ products.length }}</span>
            </p>
          </div>
          <el-table :data="products" v-loading.body="loading" stripe style="width: 100%">
            <el-table-column prop="product.PRODCHINM" label="产品中文名称" min-width="300"></el-table-column>
            <el-table-column prop="NewProductCd" label="新产品代码" min-width="150"></el-table-column>
            <el-table-column prop="product.PRODUCTCD" label="产品代码" min-width="150"></el-table-column>
            <el-table-column prop="total" label="库存数量" min-width="150" v-if="buttonName=='预拣货'"></el-table-column>
            <el-table-column prop="frozen" label="冻结数量" min-width="150" v-if="buttonName=='预拣货'"></el-table-column>
            <el-table-column prop="FineFlg" label="状态" min-width="150" v-if="buttonName!='预拣货'"></el-table-column>
            <el-table-column prop="AdjustQnty" label="受注数量" min-width="150"></el-table-column>
            <el-table-column label="操作" min-width="100">
              <template slot-scope="scope">
                <div class="action-column">
                  <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="handleChoose(scope.row)"
                  >库位</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- dialog -->
          <el-dialog
            title="出库库位"
            :visible.sync="dialogVisible"
            width="50%"
            :modal-append-to-body="false"
          >
            <p
              class="dialogVisible-title"
            >产品代码：{{ tmpGoods.NewProductCd }}, 出库数量: {{ tmpGoods.AdjustQnty }}</p>
            <el-table :data="tmpGoods.stocks" stripe style="width: 100%">
              <el-table-column prop="CHARG" label="批次号" min-width="150"></el-table-column>
              <el-table-column prop="available_time" label="有效期" min-width="150"></el-table-column>
              <el-table-column prop="location.stock_no" label="库位" min-width="150"></el-table-column>
              <el-table-column prop="state_name" label="状态" min-width="150"></el-table-column>
              <el-table-column prop="number" label="库存数量" min-width="100"></el-table-column>
              <el-table-column prop="number" label="出库数量" min-width="100" v-if="tmpGoods.tag"></el-table-column>
              <el-table-column label="出库数量" min-width="100" v-if="!tmpGoods.tag">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.actNumber"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveNumber">确 定</el-button>
            </span>
          </el-dialog>

          <!-- dialog -->
          <el-dialog
            title="防串货"
            :visible.sync="dialogCodeVisible"
            width="50%"
            :modal-append-to-body="false"
          >
            <el-table :data="codeGoods" v-loading.body="loading" stripe style="width: 100%">
              <el-table-column prop="product.PRODCHINM" label="产品中文名称" min-width="300"></el-table-column>
              <el-table-column prop="NewProductCd" label="新产品代码" min-width="150"></el-table-column>
              <el-table-column prop="AdjustQnty" label="受注数量" min-width="150"></el-table-column>
              <el-table-column label="扫描数量" min-width="150">
                <template slot-scope="scope">{{ scanNum(scope.row.id) }}</template>
              </el-table-column>
            </el-table>
            <div class="code-div">
              <el-input v-model="tmpInput" placeholder="请输入代码" id="codeInput" @keyup.enter.native="handleAdd"></el-input>
              <span style="margin-left:10px;">
                箱码:
                <span>{{ form.box_code }}</span>
              </span>
              <span style="margin-left:10px;">
                型号码:
                <span>{{ form.type_code }}</span>
              </span>
            </div>
            <el-table :data="showList" stripe style="width: 100%">
              <el-table-column prop="box_code" label="箱号" min-width="50"></el-table-column>
              <el-table-column prop="type_code" label="型号码" min-width="100"></el-table-column>
              <el-table-column prop="code" label="防串货代码" min-width="100"></el-table-column>
              <el-table-column label="操作" min-width="100">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="delCode(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="query.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="query.limit"
              layout="total,->, prev, pager, next, jumper, sizes"
              :total="codes.length"
            ></el-pagination>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogCodeVisible = false">取 消</el-button>
              <el-button type="primary" @click="dialogCodeVisible = false">确 定</el-button>
            </span>
          </el-dialog>
        </el-tab-pane>
      </el-tabs>
      <el-dialog
              title="拼箱列表"
              :visible.sync="dialogPXVisible"
              width="50%"
              :modal-append-to-body="false"
      >
        <el-table :data="pxList" stripe style="width: 100%">
          <el-table-column
                  type=""
                  width="20">
          </el-table-column>
          <el-table-column label="箱号" width="100">
            <template slot-scope="scope">
              {{ scope.row }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="downloadPX(scope.row)">下载</el-button>
            </template>
          </el-table-column>
          <el-table-column
                  type=""
                  min-width="20">
          </el-table-column>
        </el-table>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogPXVisible = false">取 消</el-button>
              <el-button type="primary" @click="dialogPXVisible = false">确 定</el-button>
            </span>
      </el-dialog>
      </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
    </div>
  </div>
</template>

<script>
import { getByNo, stockOut, rollback ,pxList} from "@/api/adjust";
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      buttonDisabled: true,
      loading: true,
      dialogVisible: false,
      dialogPXVisible: false,
      dialogCodeVisible: false,
      order: {},
      products: [],
      tmpGoods: {},
      codeGoods: [],
      is_need_code: "否",
      form: {
        box_code: "",
        type_code: ""
      },
      tmpInput: "",
      codes: [],
      pxList: [],
      buttonStatus:'',
      query: {
        limit: 10,
        page: 1
      }
    };
  },
  created() {
    this.loadOrder(this.$route.params.id);
  },
  computed: {
    buttonName() {
      if (!this.order.tag) {this.buttonStatus ='拣货';  return "预拣货"};
      if (this.order.tag.status === "拣货中") {this.buttonStatus ='拣货中'; return  "拣货"};
      if (this.order.tag.status === "复核中") {this.buttonStatus ='复核中'; return  "复核"};
      if (this.order.tag.status === "待回传") {this.buttonStatus ='待回传'; return  "回传"};
      if (this.order.tag.status === "待发运") {this.buttonStatus ='发货中'; return  "发货"};
    },
    showList() {
      let offset = this.query.limit * (this.query.page - 1);
      return this.codes.slice(offset, offset + this.query.limit);
    },
    scanNum(id) {
      return id => {
        // 统计每个型号的数量
        var ana = {};
        for (let i = 0; i < this.codes.length; i++) {
          if (this.codes[i].type_code.length == 11) {
            if (ana[this.codes[i].type_code]) {
              ana[this.codes[i].type_code] += 1;
            } else {
              ana[this.codes[i].type_code] = 1;
            }
          } else {
            let type = this.codes[i].type_code.substr(9, 11);
            let num = this.codes[i].type_code.substr(-3, 3);
            if (ana[type]) {
              ana[type] += parseInt(num);
            } else {
              ana[type] = parseInt(num);
            }
          }
        }
        for (let i = 0; i < this.codeGoods.length; i++) {
          if (ana[this.codeGoods[i].NewProductCd] && this.codeGoods[i].id == id)
            return ana[this.codeGoods[i].NewProductCd];
        }
        return 0;
      };
    }
  },
  methods: {
    loadOrder(id) {
      this.loading = true;
      getByNo({ id: id })
        .then(res => {
          this.products = res.data;
          this.codeGoods = []
          for (let i = 0; i < res.data.length; i++) {
            if (
              res.data[i].product &&
              res.data[i].product.is_need_code == "是"
            ) {
              this.is_need_code = "是";
              this.codeGoods.push(res.data[i]);
            }
          }
          this.order = res.data[0];
          setTimeout(() => {
            this.loading = false;
            this.buttonDisabled = false;
          }, 100);
        })
        .catch(error => {
          this.$router.push({
            path: "/outstorage_action/adjust"
          });
        });
    },
    handleChoose(row) {
      this.tmpGoods = row;
      this.dialogVisible = true;
    },
    handleAdd() {
      let tit = this.tmpInput
      setTimeout(() => {
        this.tmpInput = ''
        // this.$set(this.tmpData, 'tmpInput', '')
      }, 50)
      if (!this.form.box_code) {
        if (tit.length > 5) {
          alert("箱码不超过5位！");
          return;
        } else {
          this.form.box_code = tit;
        }
      } else if (!this.form.type_code) {
        if (tit.length != 11 && tit.length != 23) {
          alert("型号码11位或23位！");
          return;
        } else {
          this.form.type_code = tit;
        }
      } else {
        if (tit.length != 16) {
          alert("16位防串货码错误！");
          return;
        } else {
          for (let i = 0; i < this.codes.length; i++) {
            if (tit === this.codes[i].code) {
              alert("防串货码不能重复！");
              return;
            }
          }
          this.codes.unshift({
            type_code: this.form.type_code,
            box_code: this.form.box_code,
            code: tit
          });
          this.form.type_code = this.form.box_code = "";
        }
      }
    },
    handleSizeChange: function(val) {
      this.query.limit = val;
    },
    handleCurrentChange: function(val) {
      this.query.page = val;
    },
    delCode(row) {
      this.codes.splice(this.codes.indexOf(row), 1);
    },
    doChange() {
      this.buttonDisabled = true;
      // 是否需要防串货
      if (this.order.tag && this.order.tag.status === "待发运") {
        if (this.is_need_code === "是" && !this.codes) {
          this.$message({
            message: "未输入防串货码",
            type: "warning"
          });
          this.buttonDisabled = false;
          return;
        }
      }
      this.$message({
        message: "数据正在处理，请稍后！",
        type: "info"
      });
      stockOut({ orders: this.products, codes: this.codes ,status: this.buttonStatus})
        .then(res => {
          if (
            this.order &&
            this.order.tag &&
            this.order.tag.status === "待发运"
          ) {
            this.$message({
              message: "发货完成！",
              type: "success"
            });
            this.$router.push({
              path: "/outstorage_action/adjust"
            });
            return;
          }

        if (
                this.order &&
                this.order.tag &&
                this.order.tag.status === "拣货中"
        ) {
          this.$message({
            message: "拣货成功！",
            type: "success"
          });
        }
      if (
              this.order &&
              this.order.tag &&
              this.order.tag.status === "复核中"
      ) {
        this.$message({
          message: "复核成功！",
          type: "success"
        });
      }
      if (
              this.order &&
              this.order.tag &&
              this.order.tag.status === "待回传"
      ) {
        this.$message({
          message: "回传成功！",
          type: "success"
        });
      }
      if (
              this.order &&
              this.order.tag === null
      ) {
        this.$message({
          message: "预拣货成功！",
          type: "success"
        });
      }
          this.loadOrder(this.$route.params.id);
          this.$router.push({
            path: "/outstorage_action/adjust/out/" + this.order.OutStcNo
          });
        })
        .catch(err => {
          this.loadOrder(this.$route.params.id);
          this.buttonDisabled = false;
        });
    },
    rollback() {
      this.buttonDisabled = true;
      this.$message({
        message: "数据正在处理，请稍后！",
        type: "info"
      });
      rollback({ orders: this.products }).then(res => {
        this.$message({
          message: "回退成功！",
          type: "success"
        });
        this.loadOrder(this.$route.params.id);
        this.$router.push({
          path: "/outstorage_action/adjust/out/" + this.order.OutStcNo
        });
      });
      this.loadOrder(this.$route.params.id);
    },
    pinxiangList() {
      this.pxList = []
      pxList({vbeln:this.order.AdjustNo}).then(res => {
      this.pxList = res.data
      this.dialogPXVisible = true
    })
    },
    getSheet() {
      let token = getToken();
      token = token.split(" ", 2);
      window.open(
        "/api/adjust/exportDoc?id=" +
          this.order.AdjustNo +
          "&token=" +
          token[1],
        "_blank"
      );
    },
    downloadPX(row){
      let token = getToken()
      token = token.split(" ", 2);
      window.open(
              "/api/adjust/downloadPX?vbeln=" +
              this.order.AdjustNo + "&case=" + row +
              "&token=" +
              token[1],
              "_blank"
      );
    },
    getPDF() {
      let token = getToken();
      token = token.split(" ", 2);
      window.open(
        "/api/adjust/exportPDF?id=" +
          this.order.OutStcNo +
          "&token=" +
          token[1],
        "_blank"
      );
    },
    binning(){
      let token = getToken();
      token = token.split(" ", 2);
      window.open(
              "/api/adjust/binning?id=" +
              this.order.AdjustNo +
              "&token=" +
              token[1],
              "_blank"
      );
    },
    accept() {
      let token = getToken();
      token = token.split(" ", 2);
      window.open(
        "/api/adjust/accept?id=" + this.order.OutStcNo + "&token=" + token[1],
        "_blank"
      );
    },
    saveNumber() {
      var total = 0;
      for (let i = 0; i < this.tmpGoods.stocks.length; i++) {
        total += this.tmpGoods.stocks[i].actNumber;
        if (
          this.tmpGoods.stocks[i].actNumber > this.tmpGoods.stocks[i].number
        ) {
          this.$message({
            message: "出库数量不能超过库位存放数量",
            type: "warning"
          });
          return;
        }
      }
      if (total != this.tmpGoods.AdjustQnty) {
        this.$message({
          message: "出库数量不正确",
          type: "warning"
        });
        return;
      }
      this.dialogVisible = false;
    },
    showCodeDialog() {
      this.dialogCodeVisible = true;
    }
  }
};
</script>
<style lang="less">
.grid-container {
  height: auto;
  overflow: hidden;
  .detail-content {
    position: relative;
    height: auto;
    overflow: hidden;
    padding: 22px 15px;
    background: #fff;
    .detail-item {
      height: auto;
      overflow: hidden;
      line-height: 30px;
      font-size: 14px;
      padding-left: 30px;
      > span {
        display: inline-block;
        width: 150px;
        float: left;
        color: #333;
      }
      > div {
        margin-left: 160px;
        color: #999;
      }
    }

    .btn-box {
      position: absolute;
      top: 25px;
      right: 15px;
      z-index: 10;
    }
  }
  .action-column {
    text-align: right;
  }
  .color-gred {
    color: #999;
  }
}
.table-form-item {
  position: relative;
  height: 100%;
  width: 100%;
  .error-text {
    font-size: 12px;
    color: #f97042;
  }
}
.warehouse-select {
  margin-right: 20px;
  margin-bottom: 20px;
}
.code-div {
  display: block;
  margin: 10px 0;
  .el-input {
    display: inline-block;
    width: 200px;
  }
}
.dialogVisible-title {
  margin-bottom: 10px;
}
</style>